package com.sch.www.common.util.io;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;

import java.io.FileOutputStream;
import java.io.OutputStream;

/**
 * Created by Administrator on 2017/10/25.
 */
public class ImgUitl {
    public static Logger log = LoggerFactory.getLogger(ImgUitl.class);

    /**
     * 将base64图片保存到文件系统中
     * @param base64img base64编码字图片
     * @param pathName  图片路径+具体文件名
     * @return
     */
    public static boolean generateImage(String base64img, String pathName) {
        if (StringUtils.isBlank(base64img) || StringUtils.isBlank(pathName)) {
            return false;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        OutputStream out = null;
        try {
            // 解密
            byte[] b = decoder.decodeBuffer(base64img);
            // 处理数据
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            out = new FileOutputStream(pathName);
            out.write(b);
            return true;
        } catch (Exception e) {
            log.warn("【Manual】=>{}", e.getMessage());
            return false;
        } finally {
            try {
                out.flush();
                out.close();
            } catch (Exception e) {}
        }
    }

}
